package felix.rule.api.util;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import felix.rule.api.TNodeConfiguration;
import felix.rule.api.TNodeException;
import felix.rule.data.msg.EngineMsgMetaData;

import java.util.Map;

public class TNodeUtils {

    private static final ObjectMapper mapper = new ObjectMapper();

    private static final String VARIABLE_TEMPLATE = "${%s}";


    public static <T> T convert(TNodeConfiguration configuration, Class<T> clazz) throws TNodeException {
        try {
            return mapper.treeToValue(configuration.getData(), clazz);
        } catch (JsonProcessingException e) {
            throw new TNodeException(e);
        }
    }

    public static String processPattern(String pattern, EngineMsgMetaData metaData) {
        String result = pattern;
        for (Map.Entry<String, String> keyVal : metaData.values().entrySet()) {
            result = processVar(result, keyVal.getKey(), keyVal.getValue());
        }
        return result;
    }

    private static String processVar(String pattern, String key, String val) {
        String varPattern = String.format(VARIABLE_TEMPLATE, key);
        return pattern.replace(varPattern, val);
    }

}
